/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.pig4cloud.pigx.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.customize.enums.AbnormalEnum;
import com.pig4cloud.pigx.common.customize.exception.DuckweedException;
import com.pig4cloud.pigx.common.customize.mysql.utils.MysqlUtil;
import com.pig4cloud.pigx.common.customize.utils.id.IdWorker;
import com.pig4cloud.pigx.user.entity.*;
import com.pig4cloud.pigx.user.enums.RechargeRecordEnum;
import com.pig4cloud.pigx.user.mapper.FinanceRecordMapper;
import com.pig4cloud.pigx.user.service.FinanceRecordService;
import com.pig4cloud.pigx.user.vo.SaveFinanceDTO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 财务记录
 *
 * @author pigx code generator
 * @date 2023-02-02 16:58:30
 */
@Service
@AllArgsConstructor
public class FinanceRecordServiceImpl extends ServiceImpl<FinanceRecordMapper, FinanceRecord> implements FinanceRecordService {

	private final IdWorker idWorker;

	private final MysqlUtil mysqlUtil;

//	/**
//	 * 获取未分配的财务
//	 * @return r
//	 */
//	@Override
//	public R<UnassignedFinanceVO> getUnassigned() {
//		try {
//			List<FuelReceiveDividends> list = new FuelReceiveDividends().selectList(new QueryWrapper<FuelReceiveDividends>() {{
//				select("sum(fuel_quantity) fuelQuantity,type");
//				groupBy("type");
//			}});
//			// 总保证金
//			FuelReceiveDividends margin = list.stream().filter(e -> e.getType().equals(FuelReceiveDividendsEnums.Type.MARGIN.getValue())).collect(Collectors.toList()).get(0);
//			// 总平台纯收入
//			FuelReceiveDividends platform = list.stream().filter(e -> e.getType().equals(FuelReceiveDividendsEnums.Type.NET_INCOME.getValue())).collect(Collectors.toList()).get(0);
//			// 总市场分配
//			BigDecimal sum = BigDecimal.ZERO;
//			for (FuelReceiveDividends dividends : list) {
//				if (
//						dividends.getType().equals(FuelReceiveDividendsEnums.Type.DIRECT.getValue()) ||
//						dividends.getType().equals(FuelReceiveDividendsEnums.Type.INDIRECT.getValue()) ||
//						dividends.getType().equals(FuelReceiveDividendsEnums.Type.LEVEL_1.getValue()) ||
//						dividends.getType().equals(FuelReceiveDividendsEnums.Type.EQUALITY.getValue()) ||
//						dividends.getType().equals(FuelReceiveDividendsEnums.Type.LEVEL_2.getValue())
//				) {
//					if (dividends.getFuelQuantity() != null) {
//						sum = sum.add(dividends.getFuelQuantity());
//					}
//				}
//			}
//			List<FinanceRecord> records = new FinanceRecord().selectList(new QueryWrapper<FinanceRecord>() {{
//				select("sum(quantity) quantity,type");
//				eq("status", "1");
//				groupBy("type");
//			}});
//			BigDecimal finalSum = sum;
//			UnassignedFinanceVO financeVO = new UnassignedFinanceVO() {{
//				try {
//					// 已分配的保证金数量
//					FinanceRecord alreadyMargin = records.stream().filter(e -> "0".equals(e.getType())).collect(Collectors.toList()).get(0);
//					if (alreadyMargin != null) {
//						setMargin(margin.getFuelQuantity().subtract(alreadyMargin.getQuantity() == null ? BigDecimal.ZERO : alreadyMargin.getQuantity()));
//					} else {
//						setMargin(margin.getFuelQuantity());
//					}
//				} catch (Exception e) {
//					setMargin(margin.getFuelQuantity());
//				}
//				try {
//					// 已分配的纯收入
//					FinanceRecord alreadyPlatform = records.stream().filter(e -> "1".equals(e.getType())).collect(Collectors.toList()).get(0);
//					if (alreadyPlatform != null) {
//						setPlatform(platform.getFuelQuantity().subtract(alreadyPlatform.getQuantity() == null ? BigDecimal.ZERO : alreadyPlatform.getQuantity()));
//					} else {
//						setPlatform(platform.getFuelQuantity());
//					}
//				} catch (Exception e) {
//					setPlatform(platform.getFuelQuantity());
//				}
//				try {
//					// 已分配的市场
//					FinanceRecord alreadyPlatform = records.stream().filter(e -> "2".equals(e.getType())).collect(Collectors.toList()).get(0);
//					if (alreadyPlatform != null) {
//						setMarket(finalSum.subtract(alreadyPlatform.getQuantity() == null ? BigDecimal.ZERO : alreadyPlatform.getQuantity()));
//					} else {
//						setMarket(finalSum);
//					}
//				} catch (Exception e) {
//					setMarket(finalSum);
//				}
//			}};
//			if (financeVO.getMargin() != null) {
//				financeVO.setMargin(financeVO.getMargin().setScale(6, RoundingMode.DOWN).stripTrailingZeros());
//			}
//			if (financeVO.getPlatform() != null) {
//				financeVO.setPlatform(financeVO.getPlatform().setScale(6, RoundingMode.DOWN).stripTrailingZeros());
//			}
//			if (financeVO.getMarket() != null) {
//				financeVO.setMarket(financeVO.getMarket().setScale(6, RoundingMode.DOWN).stripTrailingZeros());
//			}
//			return R.ok(financeVO);
//		} catch (Exception e) {
//			throw new DuckweedException(AbnormalEnum.MSG.DISCONNECTED);
//		}
//	}

	@Override
	public R<String> save(SaveFinanceDTO dto) {
		try {
			mysqlUtil.startLocalTx();
			Long financeRecordId = idWorker.nextId();
			new FinanceRecord(){{
				setId(financeRecordId);
				setType(dto.getFinanceType());
				setFuelType(dto.getTransferType());
				setQuantity(dto.getQuantity());
				setChain(dto.getChain());
				setHash(dto.getHash());
				setStatus("1");
			}}.insert();
			for (Long aLong : dto.getBuyFuelIdList()) {
				new FinanceFuel(){{
					setId(idWorker.nextId());
					setFinanceRecordId(financeRecordId);
					setBuyFuelId(aLong);
				}}.insert();
			}
			mysqlUtil.commitLocalTx();
			return R.ok();
		} catch (Exception e) {
			mysqlUtil.rollbackLocalTx();
			return R.failed("记录失败!");
		}
	}

	@Override
	public R<List<TransferDetailed>> getUnassigned (String transferType, String financeType) {
		List<TransferDetailed> detailedList = baseMapper.getUnassigned(transferType, financeType);
		return R.ok(detailedList);
	}

	@Override
	public R<BigDecimal> getUserRechargeSum() {
		try {
			// 已分配的燃料包总价值
			List<FinanceFuel> fuels = new FinanceFuel().selectList(new QueryWrapper<>());
			List<Long> longs = fuels.stream().map(FinanceFuel::getBuyFuelId).collect(Collectors.toList());
			TransferDetailed transfer = longs.size() > 0 ? new TransferDetailed().selectOne(new QueryWrapper<TransferDetailed>() {{
				in("id",longs);
				select("sum(quantity) 'quantity'");
			}}) : new TransferDetailed(){{
				setQuantity(BigDecimal.ZERO);
			}};
			// 已实际分配平台收入
			FinanceRecord finance = baseMapper.selectOne(new QueryWrapper<FinanceRecord>() {{
				select("sum(quantity) 'quantity'");
				eq("type", "1");
				eq("status", "1");
			}});
			// 总人工充值
			RechargeRecord record = new RechargeRecord().selectOne(new QueryWrapper<RechargeRecord>() {{
				select("sum(quantity) 'quantity'");
				eq("type", RechargeRecordEnum.Type.USER_RECHARGE.getValue());
			}});
			BigDecimal transferNum = transfer == null || transfer.getQuantity() == null ? BigDecimal.ZERO : transfer.getQuantity().multiply(new BigDecimal("0.4"));
			BigDecimal financeNum = finance == null || finance.getQuantity() == null ? BigDecimal.ZERO : finance.getQuantity();
			BigDecimal recordNum = record == null || record.getQuantity() == null ? BigDecimal.ZERO : record.getQuantity();
			return R.ok(transferNum.subtract(financeNum).subtract(recordNum));
		} catch (Exception e) {
			throw new DuckweedException(AbnormalEnum.MSG.DISCONNECTED);
		}
	}

	@Override
	public R<BigDecimal> getUserCapitalBalanceSum(String type) {
		try {
			CapitalAccount account = new CapitalAccount().selectOne(new QueryWrapper<CapitalAccount>() {{
				if ("0".equals(type)) {
					select("sum (balance) 'balance'");
				} else {
					select("sum (frozen) 'balance'");
				}
			}});
			return R.ok(account == null || account.getBalance() == null
					? BigDecimal.ZERO
					: account.getBalance().setScale(3,RoundingMode.DOWN).stripTrailingZeros()
			);
		} catch (Exception e) {
			throw new DuckweedException(AbnormalEnum.MSG.DISCONNECTED);
		}
	}

}
